<template>
  <div class="icon-list-container">
    <div class="page-header">
      <h2>图标管理</h2>
    </div>

    <!-- 搜索和添加按钮 -->
    <div class="search-filter">
      <el-input
        v-model="searchName"
        placeholder="请输入图标名称"
        style="width: 300px; margin-right: 10px;"
        clearable
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="handleAdd">新增图标</el-button>
    </div>

    <!-- 图标列表 -->
    <el-table :data="iconsList.records" style="width: 100%" v-loading="loading">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="图标ID" width="80" />
      <el-table-column prop="iconClass" label="图标样式" width="180">
        <template #default="scope">
          <el-icon>
            <component :is="scope.row.iconClass || 'el-icon-help'" />
          </el-icon>
          <span style="margin-left: 10px;">{{ scope.row.iconClass }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="图标名称" width="180" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="iconsList.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="400px"
    >
      <el-form ref="iconFormRef" :model="iconForm" :rules="rules" label-width="80px">
        <el-form-item label="图标样式" prop="iconClass">
          <el-input v-model="iconForm.iconClass" placeholder="请输入图标样式类名" />
          <div class="icon-preview" v-if="iconForm.iconClass">
            <el-icon>
              <component :is="iconForm.iconClass || 'el-icon-help'" />
            </el-icon>
            <span>预览</span>
          </div>
        </el-form-item>
        <el-form-item label="图标名称" prop="name">
          <el-input v-model="iconForm.name" placeholder="请输入图标名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';

// 表格数据
const iconsList = ref({ records: [], total: 0 });
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索
const searchName = ref('');

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('新增图标');
const iconFormRef = ref();
const iconForm = reactive({
  id: 0,
  iconClass: '',
  name: ''
});

// 表单验证
const rules = {
  iconClass: [
    { required: true, message: '请输入图标样式类名', trigger: 'blur' },
    { max: 50, message: '图标样式不能超过50个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入图标名称', trigger: 'blur' },
    { max: 50, message: '图标名称不能超过50个字符', trigger: 'blur' }
  ]
};

// 加载图标列表
const loadIconsList = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      name: searchName.value || undefined
    };
    const res = await axios.get('/api/icon', { params });
    if (res.data.code === 200 && res.data.data) {
      iconsList.value = res.data.data;
    }
  } catch (error) {
    ElMessage.error('加载图标列表失败');
    console.error('加载图标列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadIconsList();
};

// 重置搜索
const resetSearch = () => {
  searchName.value = '';
  currentPage.value = 1;
  loadIconsList();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  loadIconsList();
};

// 当前页变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  loadIconsList();
};

// 新增图标
const handleAdd = () => {
  dialogTitle.value = '新增图标';
  Object.assign(iconForm, {
    id: 0,
    iconClass: '',
    name: ''
  });
  dialogVisible.value = true;
};

// 编辑图标
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑图标';
  Object.assign(iconForm, row);
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  try {
    await iconFormRef.value.validate();
    
    let res;
    if (iconForm.id === 0) {
      res = await axios.post('/api/icon', iconForm);
    } else {
      res = await axios.put('/api/icon', iconForm);
    }
    
    if (res.data.code === 200) {
      ElMessage.success(iconForm.id === 0 ? '新增成功' : '修改成功');
      dialogVisible.value = false;
      loadIconsList();
    }
  } catch (error) {
    console.error('提交失败:', error);
  }
};

// 删除图标
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个图标吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const res = await axios.delete(`/api/icon?idList=${id}`);
    if (res.data.code === 200) {
      ElMessage.success('删除成功');
      loadIconsList();
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
      console.error('删除失败:', error);
    }
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadIconsList();
});
</script>

<style scoped>
.icon-list-container {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.search-filter {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.icon-preview {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-preview .el-icon {
  font-size: 24px;
  margin-right: 10px;
}
</style>